package com.voodoo.lib_frame.httpTools;

import android.os.Handler;
import android.os.Looper;

import com.voodoo.lib_frame.base.BaseView;
import com.voodoo.lib_utils.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Author: voodoo
 * CreateDate: 2019/09/02 002 下午 03:44:40
 * Description: API请求
 */
public class ApiTools {

    private final static String RESULT_CODE_KEY = "code";
    private final static String RESULT_MSG_KEY = "msg";
    private final static String RESULT_SUCCESS_CODE_KEY = "0";
    Call call;
    /**
     * 发送Get请求
     *
     * @param urlStr      请求地址Url
     * @param params      请求参数
     * @param apiListener 回调监听
     */
    public void getRequest(String urlStr, RequestParams params, BaseView apiListener) {
        Request getResult = HttpRequest.createGetRequest(urlStr, params);
        call = CommonOkhttpClient.sendRequest(getResult);
        call.enqueue(new MyCallBack(urlStr, apiListener));
    }

    /**
     * 发功Paost请求
     *
     * @param urlStr      请求地址
     * @param params      请求参数
     * @param apiListener 请求回调
     */
    public void postRequest(String urlStr, RequestParams params, BaseView apiListener) {
        Request postRequest = HttpRequest.createPostRequest(urlStr, params);
        call = CommonOkhttpClient.sendRequest(postRequest);
        call.enqueue(new MyCallBack(urlStr, apiListener));
    }

    /**
     * 发功Paost请求
     *
     * @param urlStr      请求地址
     * @param json        请求参数
     * @param apiListener 请求回调
     */
    public void postJsonRequest(String urlStr, String json, BaseView apiListener) {
        Request getResult = HttpRequest.createPostJsonRequest(urlStr, json);
        call = CommonOkhttpClient.sendRequest(getResult);
        call.enqueue(new MyCallBack(urlStr, apiListener));
    }

    /**
     * 请求的回调监听类
     */
    private class MyCallBack implements Callback {
        Handler handler = new Handler(Looper.getMainLooper());
        String urlStr;
        BaseView apiListener;

        public MyCallBack(String urlStr, BaseView apiListener) {
            this.urlStr = urlStr;
            this.apiListener = apiListener;
        }

        @Override
        public void onFailure(Call call, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    apiListener.onFailure(urlStr, e.toString());
                    L.e("请求失败：" + urlStr, "IOException：" + e.toString());
                }
            });
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            final String responseStr = response.body().string();

//            if (!urlStr.endsWith("getSlots")) {
//                L.i("请求返回", "请求地址：" + urlStr, "返回数据：" + ((responseStr.equals("")) ? "无数据" : responseStr));
//            }
            L.i("请求返回", "请求地址：" + urlStr, "返回数据：" + ((responseStr.equals("")) ? "无数据" : responseStr));

            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (response.isSuccessful()) {
                        try {
                            JSONObject responseJson = new JSONObject(responseStr);
                            String codeStr = responseJson.optString(RESULT_CODE_KEY);
                            if (codeStr.equals(RESULT_SUCCESS_CODE_KEY)) {
                                apiListener.onSuccess(urlStr, responseStr);
                            } else {
                                // 走提示也走错误方法
//                                apiListener.onErrorTip(responseJson.optString(RESULT_MSG_KEY));
                                apiListener.onError(urlStr, responseJson.optString(RESULT_MSG_KEY));
                            }
                        } catch (JSONException e) {
                            apiListener.onException(e);
                            apiListener.onError(urlStr, "返回的Json格式异常");
                            L.e("返回Json值异常", "请求地址：" + urlStr, "返回数据：" + HttpRequestCode.code2String(response.code()));
                        }
                    } else {
                        L.e("返回值异常", "请求地址：" + urlStr, "返回数据：" + HttpRequestCode.code2String(response.code()));
                        apiListener.onError(urlStr, HttpRequestCode.code2String(response.code()));
                    }
                }
            });
        }

    }

    public void CallCancal(String tag) {
        CommonOkhttpClient.cancelTag(tag);
    }

}
